import axios from 'axios'
// import { getToken } from './auth.js'

const service = axios.create({
  timeout: 1000 * 30,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})

service.interceptors.request.use(
  config => {
    // const token = getToken() // 暂时使用临时 token

    // if (token) {
    //   config.headers.common.contentType = 'application/json; charset=utf-8'
    //   config.headers.common.crossDomain = true
    //   config.headers.common.Authorization = token
    // }

    // 如果是txt 或者json数据不添加请求前缀
    var ext = config.url.replace(/.+\./, '').toLowerCase()
    if (ext === 'json' || ext === 'txt' || ext === 'css') {
      config.baseURL = ''
    }

    // 获取服务端接口内部错误信息(debug = true)
    if (!config.params) {
      config.params = {}
    }
    config.params.debug = true

    if (config.method === 'get') {
      // ie 兼容模式会从缓存读取数据
      let params = config.params
      if (!params) {
        params = {}
      }

      config.params = Object.assign(params, {
        _timer304: new Date().getTime()
      })
    }

    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    // console.log('request.js  response--------------:', res)
    // 文本文件直接返回
    var ext = response.config.url.replace(/.+\./, '').toLowerCase()
    if (response.status === 200 && (ext === 'json' || ext === 'txt' || ext === 'css')) {
      return res
    } else if (response.status === 200) {
      return res
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default service
